//
//  InvestmentViewController.m
//  CBT
//
//  Created by Mr.Zhang on 2018/11/26.
//  Copyright © 2018 Mr.Zhang. All rights reserved.
//

#import "InvestmentViewController.h"
#import "RechargeListViewController.h"

#import "InvestmentCell.h"
#import "LZPickerView.h"
#import "InvestmentViewModel.h"

@interface InvestmentViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) UIButton *subMitBtn;
@property (nonatomic, strong) UIView   *textView;

@property (nonatomic, strong) LZPickerView          *lzPickerVIew;
@property (nonatomic, strong) InvestRatioModel      * investModel;
@property (nonatomic, strong) InvestmentViewModel   *viewModel;

@property (nonatomic, copy  ) NSString   *selectDays;
@end

@implementation InvestmentViewController

#pragma mark - VC Life

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = kLocalizedString(@"挖矿", nil);

    self.selectDays = @"90";
    [self.tableView endEditing:YES];
    [self startLoading];
    
    self.tableView.tableFooterView = [UIView new];
    self.tableView.backgroundColor = UIColorFromRGB(0xf1f1f1);
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    
    UITapGestureRecognizer *tableViewGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableViewTouchInSide)];
    tableViewGesture.numberOfTapsRequired = 1;
    tableViewGesture.cancelsTouchesInView = NO;
    [self.tableView addGestureRecognizer:tableViewGesture];
    
    [self inputAction];
    [self outPutAction];
    
    [self.viewModel getInvestRatioWithCoinId:[CBTLocalUserManager sharedInstance].userId];
}

- (void)tableViewTouchInSide {
    [self.view endEditing:YES];
}

#pragma mark - Input

- (void)inputAction
{
    @weak(self)
    InvestmentCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    
    [[cell.allNumBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        cell.textField.text = [self_weak_.model.coinAmount stringValue];
    }];
}

#pragma mark - OutPut
- (void)outPutAction {
    @weak(self)
    
    InvestmentCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    
    //获取利率成功
    [self.viewModel.interestSubject subscribeNext:^(InvestRatioModel *model) {
        [self_weak_ stopLoading];
        self_weak_.investModel = model;
        [cell refreshRatio:model.ratio];
//        if (self_weak_.investModel.data.count > 0) {
//            [cell refreshCellWithButtonTag:2 withDataArray:self_weak_.investModel.data];
//        }else {
//            [cell refreshNoDataCellWithSelectIndex:2];
//        }
    }];
    
    //获取利率失败
    [self.viewModel.interestSubject subscribeError:^(NSError * _Nullable error) {
        [self_weak_ stopLoading];
        [cell refreshNoDataCellWithSelectIndex:3];
    }];
    
    //投资成功
    [self.viewModel.investmentCommand.executionSignals.switchToLatest subscribeNext:^(id  _Nullable x) {
        [self_weak_ stopLoading];

        if (self_weak_.InvestmentSuccessBlock != nil) {
            self_weak_.InvestmentSuccessBlock();
        }
        [self_weak_.navigationController popViewControllerAnimated:YES];
    }];
    
    [self.viewModel.investmentCommand.errors subscribeNext:^(NSError * _Nullable x) {
        [self_weak_ stopLoading];
    }];
}

#pragma mark - 确认投资
- (void)subMitAction:(UIButton *)btn {
    InvestmentCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    
    if ([NSString isBlankString:cell.textField.text]) {
        [HFStatusView showFailureMessage:kLocalizedString(@"请输入挖矿数量",nil)];
        return;
    }
    else if ([cell.textField.text floatValue] == 0){
        [HFStatusView showFailureMessage:kLocalizedString(@"挖矿金额必须大于0",nil)];
        return;
    }
    else if ([cell.textField.text floatValue] > [self.model.coinAmount floatValue]){
        [HFStatusView showFailureMessage:kLocalizedString(@"挖矿金额大于当前可用金额",nil)];
        return;
    }
    
    [self.view endEditing:YES];
    [self startClearBgColorLoading];
    
    [self.viewModel.investmentCommand execute:@{@"userID":[CBTLocalUserManager sharedInstance].userId,@"coinId":self.model.coinId,@"num":cell.textField.text,@"day":self.selectDays}];
}

#pragma mark - 跳转投资记录
- (IBAction)investmentListACtion:(UIBarButtonItem *)sender {
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    RechargeListViewController *vc = [story instantiateViewControllerWithIdentifier:@"rechargeListVC"];
    vc.showListType = 1;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        InvestmentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
        cell.backgroundColor = UIColorFromRGB(0xF1F1F1);
        cell.numLabel.text   = self.model.coinSymbol;
        [cell.iconImageView lf_setImageURL:[NSString stringWithFormat:@"%@/%@",kBaseURL_PICSTATIC,self.model.coinPic]];
        
//        [cell setDaysBtnClickBlock:^(NSInteger selectIndex, NSString * _Nonnull days) {
//            if ([days isEqualToString:self_weak_.selectDays]) {
//                return;
//            }
//            self_weak_.selectDays = days;
//            BOOL isPresence = NO;
//            for (int i = 0; i < self_weak_.investModel.data.count; i++) {
//                InvestRatioItemModel *model = self_weak_.investModel.data[i];
//                if ([model.investDuration isEqualToString:days]) {
//                    model.isCellSelect = YES;
//                    isPresence = YES;
//                }else{
//                    model.isCellSelect = NO;
//                }
//            }
//
//            if (!isPresence) {
//                [weakCell refreshNoDataCellWithSelectIndex:selectIndex];
//            }else{
//                [weakCell refreshCellWithButtonTag:selectIndex withDataArray:self_weak_.investModel.data];
//            }
//        }];
        
        return cell;
    }
    else if (indexPath.row == 1) {
        static NSString *iden = @"PushCellId";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:iden];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:iden];
            cell.backgroundColor = UIColorFromRGB(0xF1F1F1);
            cell.selectionStyle  = UITableViewCellSelectionStyleNone;
            
            _subMitBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 38, ScreenNarrowSide - 30,40)];
            _subMitBtn.backgroundColor     = DefaultOrangeColor;
            _subMitBtn.layer.cornerRadius  = 20;
            _subMitBtn.layer.masksToBounds = YES;
            _subMitBtn.titleLabel.font     = [UIFont systemFontOfSize:16];
           
            [_subMitBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
            [_subMitBtn setTitle:kLocalizedString(@"确认", nil) forState:(UIControlStateNormal)];
            [_subMitBtn addTarget:self action:@selector(subMitAction:) forControlEvents:(UIControlEventTouchUpInside)];
           
            [cell.contentView addSubview:_subMitBtn];
        }
        
        return cell;
    }
    else {
        static NSString *iden = @"PushCellId";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:iden];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:iden];
            cell.backgroundColor = UIColorFromRGB(0xF1F1F1);
            cell.selectionStyle  = UITableViewCellSelectionStyleNone;
            
            NSString *text = kLocalizedString(@"温馨提示：\n\n\n1.每笔挖矿都可在“我的收益”中查看。\n\n2.您的收益每日会以PC形式存到您的账户中。\n\n3.用户级别不同对应的预期日回报率不同。\n\n4.数字货币有风险，请谨慎投资。",nil);
            CGFloat height = [NSString sizeWithString:text font:[UIFont systemFontOfSize:13] width:ScreenNarrowSide - 60 height:0];
            
            UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(15, 77, ScreenNarrowSide - 30, height + 41)];
            bottomView.backgroundColor     = [UIColor whiteColor];
            bottomView.layer.cornerRadius  = 5;
            bottomView.layer.masksToBounds = YES;
            [cell.contentView addSubview:bottomView];
            
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15, 19, bottomView.width - 30, height)];
            label.numberOfLines = 0;
            label.lineBreakMode = NSLineBreakByCharWrapping;
            label.text = text;
            label.font = [UIFont systemFontOfSize:13];
            label.textColor = UIColorFromRGB(0x999999);
            [bottomView addSubview:label];
        }
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return indexPath.row == 0 ?
    201 : indexPath.row == 1  ?
    78  : [NSString sizeWithString:kLocalizedString(@"温馨提示：\n\n\n1.每笔挖矿都可在“我的收益”中查看。\n\n2.您的收益每日会以PC形式存到您的账户中，且数额会根据具体币种的价格浮动而变化。\n\n3.预期日回报率会略有浮动，挖矿以当日利率为准，挖矿完的存单不会根据预期回报率浮动。\n\n4.存单到期后您可选择提取本金和续存，如不选择，两天后自动续存。\n\n5.数字货币有风险，请谨慎投资。",nil)
    font:[UIFont systemFontOfSize:13] width:ScreenNarrowSide-60 height:0]+141;
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSMutableString *s = [NSMutableString stringWithFormat:@"%@",textField.text];
    [s insertString:string atIndex:range.location];
    if ([s SizeCount] > 4 || ([s isEqualToString:@"."] && [NSString isBlankString:textField.text])) {
        return NO;
    }
    if (![NSString validateNumber:string]) {
        return NO;
    }
    if ([textField.text containsString:@"."] && [string isEqualToString:@"."]) {
        return NO;
    }
    return YES;
}

#pragma mark - Lazy
- (InvestmentViewModel *)viewModel
{
    if (!_viewModel) {
        _viewModel = [[InvestmentViewModel alloc] init];
    }
    return _viewModel;
}

@end
